    /** 
    * PTurlmigration -  http://code.google.com/p/alui-toolbox/
    * Copyright (c) 2008-2009
    * by Fabien Sanglier
    *
    * This file is part of PTurlmigration.
    * 
    * PTurlmigration is free software: you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation, either version 3 of the License, or
    * (at your option) any later version.
    * 
    * PTurlmigration is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    * 
    * You should have received a copy of the GNU General Public License
    * along with PTurlmigration.  If not, see <http://www.gnu.org/licenses/>.
    */
    
package com.ppc.ptmigration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.plumtree.openfoundation.util.IXPPropertyBag;
import com.plumtree.openkernel.config.IOKContext;
import com.plumtree.openkernel.factory.OKConfigFactory;
import com.plumtree.server.IPTCard;
import com.plumtree.server.IPTCardPropertyValues;
import com.plumtree.server.IPTGadgetContentServer;
import com.plumtree.server.IPTObjectManager;
import com.plumtree.server.IPTQueryResult;
import com.plumtree.server.IPTServerConfigSettings;
import com.plumtree.server.IPTSession;
import com.plumtree.server.IPTWebService;
import com.plumtree.server.PT_CLASSIDS;
import com.plumtree.server.PT_GLOBALOBJECTS;
import com.plumtree.server.PT_PROPIDS;
import com.plumtree.server.PT_SERVER_CONFIG_SETTINGNAME;
import com.plumtree.server.PortalObjectsFactory;
import com.plumtree.xpshared.config.ConfigPathResolver;

public class MigrateUtil {
	public final static String DEFAULT_APP_NAME = "portal";

	private IPTSession ptsession = null;

	private Pattern p = null;

	private String replacement = null;

	private boolean isDebug = false;

	public Pattern getP() {
		return p;
	}

	public void setP(Pattern p) {
		this.p = p;
	}

	public String getReplacement() {
		return replacement;
	}

	public void setReplacement(String replacement) {
		this.replacement = replacement;
	}

	public MigrateUtil(String appName, String username, String password,
			String regexpPattern, String strReplacement, boolean debug) {
		super();
		
		System.out.println("Start Session Initialization");
		ptsession = initSession(appName);
		
		System.out.println("Try to perform the Session Connect");
		
		ptsession.Connect(username, password, null);
		System.out.println("Session Connect Successful");
		
		//implement the regexp expression
		p = Pattern.compile(regexpPattern, Pattern.CASE_INSENSITIVE);
		replacement = strReplacement;
		isDebug = debug;
	}

	public MigrateUtil(String appName, String username, String password,
			String regexpPattern, String strReplacement) {
		this(appName,username,password,regexpPattern,strReplacement,false);
	}
	
	public void Dispose() {
		ptsession = null;
		p = null;
		replacement = null;
	}

	private IPTSession initSession(String sApplicationName) {
		//Initialize OpenKernel, telling OpenConfig where to get it's stuff
		String strServerConfigDir = ConfigPathResolver.GetOpenConfigPath();

		if (sApplicationName == null)
			sApplicationName = DEFAULT_APP_NAME;

		IOKContext configContext = OKConfigFactory.createInstance(
				strServerConfigDir, sApplicationName);
		PortalObjectsFactory.Init(configContext);
		
		//connect using the Portal Server Session
		return PortalObjectsFactory.CreateSession();
	}

	private void showResultPropertyValues(IPTQueryResult results, int resultRow) {
		for (int j = 0; j < results.Columns().length; j++) {
			System.out.println(results.ItemAsObject(resultRow, results
					.Columns()[j]));
		}
	}

	public void migrateRemoteServerObjects() {
		System.out
				.println("================== REMOTE SERVER OBJECTS ============================");

		IPTObjectManager gadgetServerManager = ptsession
				.GetGadgetContentServers();

		Object[][] vQueryFilter = new Object[3][1];
		/*
		 vQueryFilter[0][0]=new Integer(PT_PROPIDS.PT_PROPID_PROP_HREF);
		 vQueryFilter[1][0]=new Integer(PT_FILTEROPS.PT_FILTEROP_CONTAINS);
		 vQueryFilter[2][0]="ubuntu";
		 vQueryFilter[0][0]=new Integer(PT_PROPIDS.PT_PROPID_OBJECTID);
		 vQueryFilter[1][0]=new Integer(PT_FILTEROPS.PT_FILTEROP_NE);
		 vQueryFilter[2][0]="2";
		 */
		vQueryFilter = null;

		String url = "";

		IPTQueryResult results = gadgetServerManager.Query(
				PT_PROPIDS.PT_PROPID_ALL, -1, PT_PROPIDS.PT_PROPID_OBJECTID, 0,
				-1, vQueryFilter);

		IPTGadgetContentServer objRemoteServer = null;
		Matcher match = null;
		for (int i = 0; i < results.RowCount(); i++) {
			System.out.println("Web Service Object: " + results.ItemAsString(i, PT_PROPIDS.PT_PROPID_NAME));
			
			if (isDebug)
				showResultPropertyValues(results, i);

			try {
				objRemoteServer = (IPTGadgetContentServer) gadgetServerManager
						.Open(results.ItemAsInt(i,
								PT_PROPIDS.PT_PROPID_OBJECTID), true);
				url = objRemoteServer.GetURL();

				if (isDebug)
					System.out.println("original url:" + url);

				match = p.matcher(url);

				if (match.find()) {
					System.out.println("Pattern " + p.pattern() + " FOUND");
					url = match.replaceAll(replacement);

					if (isDebug)
						System.out.println("modified url:" + url);

					objRemoteServer.SetURL(url);
					objRemoteServer.Store();

					System.out.println("-----successfully saved object-------");
				} else {
					System.out.println("Pattern " + p.pattern() + " not found");
				}
			} catch (Exception exc) {
				System.out.println("An exception occured: " + exc);
			} finally {
				if (objRemoteServer != null)
					objRemoteServer.UnlockObject();
			}
		}
	}

	public void migrateWebServiceObjects() {
		System.out
				.println("================== WEB SERVICE OBJECTS ============================");

		IPTObjectManager webserviceManager = ptsession.GetWebServices();
		IPTQueryResult results = webserviceManager.Query(
				PT_PROPIDS.PT_PROPID_ALL, -1, PT_PROPIDS.PT_PROPID_OBJECTID, 0,
				-1, null);

		IPTWebService objWebService = null;
		Matcher match = null;
		for (int i = 0; i < results.RowCount(); i++) {
			System.out.println("Web Service Object: " + results.ItemAsString(i, PT_PROPIDS.PT_PROPID_NAME));
			
			if (isDebug)
				showResultPropertyValues(results, i);

			try {
				objWebService = (IPTWebService) webserviceManager.Open(results
						.ItemAsInt(i, PT_PROPIDS.PT_PROPID_OBJECTID), true);
				IXPPropertyBag bag = objWebService.GetProviderInfo();
				String strProperty = bag.toString();

				if (isDebug) {
					System.out.println("Web Service Name:"
							+ objWebService.GetName());
					System.out.println("original xml property:" + bag);
				}

				match = p.matcher(strProperty);
				if (match.find()) {
					System.out.println("Pattern " + p.pattern() + " FOUND");

					strProperty = match.replaceAll(replacement);

					// load the new property into the XPPropertyBag object
					bag.LoadFromXML(strProperty);

					if (isDebug)
						System.out.println("modified xml property:" + bag);

					objWebService.SetProviderInfo(bag);
					objWebService.Store();
					System.out.println("-----successfully saved object-------");
				} else {
					System.out.println("Pattern " + p.pattern() + " not found");
				}
			} catch (Exception exc) {
				System.out.println("An exception occured: " + exc);
			} finally {
				if (objWebService != null)
					objWebService.UnlockObject();
			}
		}
	}

	public void migrateServerConfigObjects() {
		System.out
				.println("================== SERVER CONFIG OBJECTS ============================");

		//get the config object
		IPTServerConfigSettings config = (IPTServerConfigSettings) ptsession
				.OpenGlobalObject(
						PT_GLOBALOBJECTS.PT_GLOBAL_SERVERCONFIGSETTINGS, true);

		String url = "";

		//set the setting array
		int[] iaSettingIDs = {
				PT_SERVER_CONFIG_SETTINGNAME.PT_SETTINGNAME_PLUMTREE_WEBSERVER_URL,
				PT_SERVER_CONFIG_SETTINGNAME.PT_SETTINGNAME_PLUMTREE_DISPLAYFILESDIRECTORY_URL,
				PT_SERVER_CONFIG_SETTINGNAME.PT_SETTINGNAME_PLUMTREE_SOAPAPI_URL,
				PT_SERVER_CONFIG_SETTINGNAME.PT_SETTINGNAME_PLUMTREE_OPENFEDERATEDSEARCH_URL };

		//The 0th column contains the setting ID for the row (which will correspond to one of the values in PT_SERVER_CONFIG_SETTINGNAME, 
		//and the 1st column contains the value for that setting.
		Object[][] settingValues = config.GetSettings(iaSettingIDs);
		Matcher match = null;
		for (int i = 0; i < settingValues.length; i++) {
			if (isDebug)
				System.out.println("PT_SERVER_CONFIG_SETTINGNAME:"
					+ settingValues[i][0] + ":" + settingValues[i][1]);

			if (settingValues[i][1] != null) {
				url = settingValues[i][1].toString();

				if (isDebug)
					System.out.println("original url:" + url);

				match = p.matcher(url);
				if (match.find()) {
					System.out.println("PT_SERVER_CONFIG_SETTINGNAME:" + settingValues[i][0]);
					System.out.println("Pattern " + p.pattern() + " FOUND");

					url = match.replaceAll(replacement);

					if (isDebug)
						System.out.println("modified url:" + url);

					try {
						config.SetSetting(new Integer(settingValues[i][0]
								.toString()).intValue(), url);
						System.out
								.println("-----successfully saved object-------");
					} catch (Exception ex) {
						System.out.println("Error : " + ex);
					}
				} else {
					System.out.println("Pattern " + p.pattern() + " not found");
				}
			}
		}
	}
	public void migrateCardObjects() {
		System.out
				.println("================== CARD OBJECTS ============================");

		IPTObjectManager cardsManager = ptsession.GetObjectManagers(PT_CLASSIDS.PT_CATALOGCARD_ID);
		IPTQueryResult results = cardsManager.Query(
				PT_PROPIDS.PT_PROPID_ALL, -1, PT_PROPIDS.PT_PROPID_OBJECTID, 0,
				-1, null);

		IPTCard objCard = null;
		Matcher match = null;
		for (int i = 0; i < results.RowCount(); i++) {
			System.out.println("Card Object: " + results.ItemAsString(i, PT_PROPIDS.PT_PROPID_NAME));
			
			if (isDebug)
				showResultPropertyValues(results, i);

			try {
				objCard = (IPTCard) cardsManager.Open(results
						.ItemAsInt(i, PT_PROPIDS.PT_PROPID_OBJECTID), true);
				
				String strDocUrl = objCard.GetDocumentURL();
								
				if (isDebug) {
					System.out.println("Card Object Name:"
							+ objCard.GetName());
					System.out.println("original Document URL:" + strDocUrl);
				}

				match = p.matcher(strDocUrl);
				if (match.find()) {
					System.out.println("Pattern " + p.pattern() + " FOUND");

					strDocUrl = match.replaceAll(replacement);

					if (isDebug)
						System.out.println("modified Document URL:" + strDocUrl);

					objCard.SetDocumentURL(strDocUrl);
					objCard.Store();
					System.out.println("-----successfully saved object-------");
				} else {
					System.out.println("Pattern " + p.pattern() + " not found");
				}
			} catch (Exception exc) {
				System.out.println("An exception occured: " + exc);
			} finally {
				if (objCard != null)
					objCard.UnlockObject();
			}
		}
	}

}
